package com.hhd.pdf.components;

import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.exceptions.PdfException;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ComponentsDelegate {
    @Autowired
    List<PdfComponent> pdfComponentList;

    public void parseComponent(Element element, GeneratorContext context) {
        PdfComponent component = getComponent(element);
        try {
            if (!component.has(element, context)) {
                return;
            }
            component.parseComponent(element, context);
        } catch (Exception e) {
            throw new PdfException(e);
        }
    }

    private PdfComponent getComponent(Element element) {
        String name = element.getName();
        for (PdfComponent component : pdfComponentList) {
            if(component.getName().toLowerCase().equals(name.toLowerCase()))
                return component;
        }
        throw new PdfException("不支持的组件: " + name);
    }
}
